#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstring>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt=0;
    while(true)
    {
        snprintf(buffer,sizeof(buffer)-1,"i am child,pid:%d,cnt:%d",getpid(),cnt++);
        write(wfd,buffer,strlen(buffer));
        sleep(2);
        //break;
    }
}
void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        //sleep(5);
        buffer[0]=0;
        ssize_t n = read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"child say: "<<buffer<<std::endl;
            //sleep(2);
        }
        else
        {
            std::cout<<"n:"<<n<<std::endl;
            std::cout<<"子进程退出，我也退出"<<std::endl;
            break;
        }
    }
}

int main()
{
    int fd[2]={0};
    int n=pipe(fd);
    if(n < 0)
    {
        std::cerr<<"pipe"<<std::endl;
        return 1;
    }
    pid_t id=fork();
    if(id==0)
    {
        //child
        //关闭读，让子进程写
        close(fd[0]);
        
        ChildWrite(fd[1]);

        close(fd[1]);
        exit(0);
    }
    //father
    close(fd[1]);
    FatherRead(fd[0]);
    
    int status=0;
    int ret = waitpid(id,&status,0);
    if(ret>0)
    {
        printf("exit code:%d,exit signal:%d\n",(status>>8)&0xFF,status&0x7F);
    }
    close(fd[0]);
    return 0;
}